package com.example.demoserver.controller;

import com.example.demoserver.entity.HousePartstore;
import com.example.demoserver.entity.HouseProduct;
import com.example.demoserver.service.impl.HouseProductServiceImpl;
import com.fazecast.jSerialComm.SerialPort;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/com")
@RequiredArgsConstructor
@Component
public class comController {
    SerialPort ncom=null;
    private final HouseProductServiceImpl houseProductService;
    @GetMapping("/selectcom")
    public List<Map> selectCom(Integer type) {
        SerialPort[] comPort = SerialPort.getCommPorts();
        List<Map> list=new ArrayList<>();

        for (SerialPort s: comPort) {
            Map<String,String> map=new HashMap();
            map.put("value",s.getSystemPortName());
            map.put("label",s.getSystemPortName());
            list.add(map);
        }
        return list;
    }
    @GetMapping("/opencom")
    public String openCom(String com) {
        SerialPort[] comPort = SerialPort.getCommPorts();
        for (SerialPort s: comPort) {
            if(s.getSystemPortName().equals(com)){
                s.openPort();
                if(s.isOpen()) {
                    if(ncom!=null){
                        ncom.closePort();
                    }
                    ncom=s;
                    s.setComPortParameters(9600, 8, 1, SerialPort.NO_PARITY);
                    s.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
                    Scanner data = new Scanner(s.getInputStream());
                    while (data.hasNextLine()) {
                        try {
                            String line = data.nextLine();
                            // 打印字符串数据
                            return  line;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return "200";
                }
            }
        }
        return "500";
    }
    @GetMapping("/closecom")
    public boolean closeCom() {
        boolean bol=ncom.closePort();
        return bol;
    }
    @PostMapping("/updatepro")
    public boolean UpdatePro(@RequestBody HouseProduct houseProduct) {
        boolean bol=houseProductService.updateById(houseProduct);
        return bol;
    }

}
